package org.shop.controller.common;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.Users;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.UserService;
import org.shop.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UpdatePasswordController {

	private static Logger logger = LogManager.getLogger(UpdatePasswordController.class);
	
	@Autowired
	private UserService userService;
	
	/**
	 * 修改密码（后台公供接口）
	 * @param req
	 * @return
	 */
	@RequestMapping("common/updatePassWord")
	@ResponseBody
	public int updatePassWord(HttpServletRequest req) {
		int num = 0 ;
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String passWordNew = req.getParameter("passwordNew");
		String passwordOld = req.getParameter("passwordOld");
		try {
			if(MD5Util.MD5(passwordOld).equals(ud.getPassword())) {
				Users user = new Users();
				user.setUserId(ud.getUserId());
				user.setPassword(MD5Util.MD5(passWordNew));
				num = userService.updateByPrimaryKeySelective(user);
			}else {
				num = -1;
			}
		}catch(Exception e) {
			num = 0;
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return num;
	}
	
	
}
